from bs4 import BeautifulSoup
from common import get_structured_text, save_file


# TODO 解析【办校历史】
def resolveHistory(obj):
    href = obj["href"]
    title = obj["title"]
    content = obj["content"]
    soup = BeautifulSoup(content, 'html.parser')
    clearfix_div = soup.find('div', class_='box f16p')
    mainTitle = get_structured_text(clearfix_div)
    subs = soup.find_all('li', class_='clearfix wow slideInUp')

    result = {"mainTitle": mainTitle, "subs": []}

    for sub in subs:
        img = sub.find('img')['src']
        subTitle = sub.find('h3').text.strip()
        descP = sub.find('p', class_="fontp")
        content = get_structured_text(descP)
        result["subs"].append({"subTitle": subTitle, "img": img, "content": content})

    save_file(result, title + ".json")


# TODO 解析【办学理念】
def resolveIdea(obj):
    href = obj["href"]
    title = obj["title"]
    content = obj["content"]
    soup = BeautifulSoup(content, 'html.parser')
    clearfix_div = soup.find('dl', class_='clearfix wow slideInUp')
    dts = clearfix_div.find_all('dt', class_='f24 ca02')
    dds = clearfix_div.find_all('dd', class_='f18')

    result = []
    for index in range(len(dts)):
        subTitle = dts[index].text.strip()
        content = get_structured_text(dds[index])
        result.append({"title": subTitle, "content": content})

    save_file(result, title + ".json")


# TODO 解析【校园景色】

def resolveView(obj):
    href = obj["href"]
    title = obj["title"]
    content = obj["content"]
    soup = BeautifulSoup(content, 'html.parser')
    div = soup.find('div', 'view content')
    ul = div.find('ul', class_='clearfix')
    items = ul.find_all('li')

    result = []

    for item in items:
        subTitle = item.find('p').text.strip()
        linkNodes = item.find_all('a')

        links = []

        for linkNode in linkNodes:
            link_title = linkNode['data-caption']
            link_img = linkNode['href']
            links.append({"name": link_title, "img": link_img})

        result.append({"subTitle": subTitle, "items": links})

    save_file(result, title + ".json")
